package com.gainloop;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;

import org.alexd.jsonrpc.JSONRPCException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.*;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.gainloop.R;
import com.gainloop.Api.Wishes;
import com.gainloop.Api.Wishes.SearchType;
import com.gainloop.Api.Entity.Tag;
import com.gainloop.Api.Entity.WishEx;
import com.gainloop.Utils.Constants;
import com.gainloop.Utils.ConvertUtils;

public class SearchResults extends ActivityAbstract {
	private ArrayList<WishEx> wishes = null;
	private WishAdapter adapter;
	private Runnable viewWishes;
	private ProgressDialog progressDialog = null;
	
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result_list);
		initHeader();
		headerTitle.setText(R.string.results);
		ListView mListView = (ListView) findViewById(R.id.searchResultList);
		 
		adapter = new WishAdapter(this, R.layout.wish_item, new ArrayList<WishEx>());
		mListView.setAdapter(adapter);
		
		//listType = (ListType)getIntent().getExtras().get(Constants.listTypeParam);
		
		viewWishes = new Runnable() {
			@Override
			public void run() {
				Long categoryId=getCategoryId();
				SearchType type=(SearchType) getIntent().getExtras().get(Constants.SEARCH_TYPE);
				ArrayList<Tag> tagArr=getTagsArr();
				try {
					if (tagArr==null&&categoryId==null){
						if (type==SearchType.NORMAL){
							wishes=Wishes.getInstance().getTopWishes(1);
						}
						else{
							wishes=Wishes.getInstance().getFriendsWishes(1);
						}
					}
					else{
						wishes=Wishes.getInstance().search(categoryId, tagArr,type, 1);

					}
					} catch (JSONRPCException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						throw new RuntimeException("Error - getting search results");
					}
				runOnUiThread(returnRes);
				//wishes=(ArrayList<WishEx>)getIntent().getExtras().get(Constants.wishesParam);

			}
		};
		Thread thread = new Thread(null, viewWishes, "MagentoBackground");

		progressDialog = ProgressDialog.show(SearchResults.this, getString(R.string.wait_msg),
			getString(R.string.ret_data_msg), true);
		thread.start();

		//ListView lv = getListView();
		mListView.setTextFilterEnabled(true);

		mListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				WishEx wish=adapter.getItem(position);
				
//				Toast.makeText(getApplicationContext(), "Wish Id: "+wish.getId(),
//						Toast.LENGTH_SHORT).show();

				Intent intent=new Intent(SearchResults.this,GainPage.class)
					.putExtra(GainPage.GAIN_ID, wish.getId());
				SearchResults.this.startActivity(intent);
				
			}

			
		});

	}
/*
	private void getWishes() {
		try {
			switch (listType){
			case TOP:
				wishes = Wishes.getInstance().getTopWishes(1);
				break;
			case RECENT:
				wishes = Wishes.getInstance().getRecentWishes(1);
				break;
			case FRIENDS:
				wishes = Wishes.getInstance().getFriendsWishes(1);
				break;
			case USER:
				wishes = Wishes.getInstance().getUserWishes(Registry.GetUser(), 1);
				break;
			case SEARCH_CATEGORY:		
				wishes = searchByCategory();
				Log.v("amount of wishes",Integer.toString(wishes.size()));
				break;	
			case SEARCH_TAGS:
				wishes = searchByTags();
				Log.v("amount of wishes",Integer.toString(wishes.size()));
				break;
			case SEARCH_BOTH:
				wishes = searchByTagsAndCategory();
				Log.v("amount of wishes",Integer.toString(wishes.size()));
				break;
			}
		} catch (JSONRPCException e) {
			Constants.declareInternalError(getApplicationContext());
			e.printStackTrace();
		}
		runOnUiThread(returnRes);
	}
	
	
	

	/**
	 * Fetch the search result from server by tags only.
	 * @return the Wish array that correspond to tags array given on the intent.
	 * @throws JSONRPCException 
	 */
	/*
	private ArrayList<WishEx> searchByTags() throws JSONRPCException {
		ArrayList<Tag> tagList = getTagsArr();
		return Wishes.getInstance().search(null, tagList, SearchType.NORMAL, 1);
	}

	

	/**
	 * Fetch the search result from server by category only.
	 * @return the Wish array that correspond to category given on the intent.
	 * @throws JSONRPCException 
	 *//*
	private ArrayList<WishEx> searchByCategory() throws JSONRPCException {
		Long categoryId = getCategoryId();
		return Wishes.getInstance().search(categoryId, null, SearchType.NORMAL, 1);
	}
	
	/**
	 * Fetch the search result from server by category and tags.
	 * @return the Wish array that correspond to category and tags given on the intent.
	 * @throws JSONRPCException
	 *//*
	private ArrayList<WishEx> searchByTagsAndCategory() throws JSONRPCException {
		Long categoryId = getCategoryId();
		ArrayList<Tag> tagList = getTagsArr();
		
			
		return Wishes.getInstance().search(categoryId, tagList, SearchType.NORMAL, 1);
	}
	*/
	/**
	 * Gets the tags list from the current intent.
	 * @return Tag array list.
	 */
	private ArrayList<Tag> getTagsArr() {
		ArrayList<String> tagsArr = getIntent().getExtras().getStringArrayList(Constants.TAGS_STRING_ARR_KEY);
		if (tagsArr==null)
			return null;
		Log.v("number of tags",Integer.toString(tagsArr.size()));
		
		return ConvertUtils.transformToTagList(new LinkedList<String>(tagsArr));

	}
	
	/**
	 * Gets the category id from the current intent.
	 * @return CategoryId.
	 */
	private Long getCategoryId() {
		return getIntent().getExtras().getLong(Constants.CATEGORY_ID);
	}

	
	

	private class WishAdapter extends ArrayAdapter<WishEx> {

		private ArrayList<WishEx> items;

		public WishAdapter(Context context, int textViewResourceId,
				ArrayList<WishEx> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.wish_item, null);
			}
			WishEx item = items.get(position);
			if (item != null) {
				ImageView profile = (ImageView) v
						.findViewById(R.id.wishItemProfileImg);
				TextView content = (TextView) v
						.findViewById(R.id.wishItemContent), username = (TextView) v
						.findViewById(R.id.wishItemUsername), category = (TextView) v
						.findViewById(R.id.wishItemCategory), helps = (TextView) v
						.findViewById(R.id.wishItemHelps);

				try {
					URL newurl = new URL(
							"http://graph.facebook.com/" + item.getUserFbId() + "/picture?type=square");
					Bitmap bitmap = BitmapFactory.decodeStream(newurl
							.openConnection().getInputStream());
					profile.setImageBitmap(bitmap);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				username.setText(item.getUserName());
				content.setText(item.getContentShort());
				category.setText(item.getCategoryName());
				helps.setText("" + item.getHelpsNum());
			}
			return v;
		}
	}

	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			if (wishes != null && wishes.size() > 0) {
				adapter.notifyDataSetChanged();
				
				for (int i = 0; i < wishes.size(); i++){
					adapter.add(wishes.get(i));
				}
			}
			progressDialog.dismiss();
			adapter.notifyDataSetChanged();
		}
	};
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		
		MenuItem mi_profile = menu.findItem(R.id.menuProfile);
		mi_profile.setIntent(new Intent(this, Profile.class));
		
		MenuItem mi_newWish = menu.findItem(R.id.menuNewWish);
		mi_newWish.setIntent(new Intent(this, AddWish.class));
		
		MenuItem mi_home_gain = menu.findItem(R.id.menuHome); 
		mi_home_gain.setIntent(new Intent(this, Home.class));
		
		MenuItem mi_search_gain = menu.findItem(R.id.menuSearch); 
		mi_search_gain.setIntent(new Intent(this, GainSearch.class));
		
		MenuItem mi_people = menu.findItem(R.id.menuPeople); 
		mi_people.setIntent(new Intent(this, People.class));
		
		
		return true;
	}

}